package apiauth

import (
	"bysy-gin/handler"
	"bysy-gin/model"
	"crypto/md5"
	"encoding/hex"
	"github.com/gin-gonic/gin"
	"io"
)

func ApiAuth(c *gin.Context) bool {
	//url参数
	signature := c.Query("sign")
	appid := c.Query("appid")
	timestamp := c.Query("timestamp")

	//可以判断是否过期

	//通过appid去查找secretkey
	var a model.ApiAuth
	a.AppId = appid
	if err := a.GetKey(); err != nil {
		handler.SendResponse(c, 1007, "appid错误!", nil)
		return false
	}
	message := appid + timestamp + a.SecretKey
	if signature != GenerateSign(message) {
		return false
	}
	return true
}

func GenerateSign(message string) string {
	hashobj := md5.New()
	//写入数据到哈希对象中
	io.WriteString(hashobj, message)
	//计算哈希值
	hashbytes := hashobj.Sum(nil)
	//转化字符串16进制
	hashstring := hex.EncodeToString(hashbytes)
	return hashstring
}
